<script lang="ts" setup>
import { computed, ref, reactive, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { storeToRefs } from 'pinia' // 引入关键工具函数
import { tableDataStoreHook } from '@store/dataStore'
import { historyDataStoreHook } from '@store/historyStore'
import { useScrollStoreHook } from '@store/scrollStore'
import ContextMenu from './rightClickMenu/ContextMenu.vue'
import { items, ArrayType } from '@renderer/api/quote/types'
import { ElMessageBox, ElMessage } from 'element-plus'

// 获取 store 实例
const tableDataStore = tableDataStoreHook()
const historyDataStore = historyDataStoreHook()
const scrollStore = useScrollStoreHook()

// 使用 storeToRefs 解构响应式状态[1,2](@ref)
const {
  buysList,
  discountList,
  total,
  discountTotal,
  buyTotal,
  specialNum,
  special,
  isBillingBoolean
} = storeToRefs(tableDataStore)
const { serial_number } = storeToRefs(historyDataStore)
// 计算属性改为基于解构后的响应式状态
const buysLen = computed(() => buysList.value.length)
const discountLen = computed(() => discountList.value.length)

// const special = ref<boolean>(false)
const isCaptureMode = ref(false)
const contextMenuVisible = ref(false)
const contextMenuPosition = reactive({ x: 0, y: 0 })

const selectedRowIndex = ref(-1)
const selectedRowType = ref('')
const tableBody = ref<HTMLElement | null>(null)
const rowRefs = ref<{ [key: string]: HTMLElement[] }>({ discount: [], buy: [] })
// 设置行的引用
const setRowRef = (el: HTMLElement | null, type: string, index: number) => {
  if (el) {
    if (!rowRefs.value[type]) {
      rowRefs.value[type] = []
    }
    rowRefs.value[type][index] = el
  }
}
// 选中单行
const selectRow = (index: number, type: string) => {
  console.log('selectRow')
  console.log(index)
  console.log(type)
  selectedRowIndex.value = index
  selectedRowType.value = type
  console.log(selectedRowIndex.value)
  console.log(selectedRowType.value)
  tableDataStore.getClickItem(type == 'discount' ? 'discountList' : 'buysList', index)
  closeContextMenu()
}

// 滚动到最新一行函数
const scrollToLatestRow = (type: 'discountList' | 'buysList') => {
  // 等待DOM更新完成
  nextTick(() => {
    const refKey = type === 'discountList' ? 'discount' : 'buy'
    const listLength = type === 'discountList' ? discountLen.value : buysLen.value

    if (listLength > 0) {
      const lastRow = rowRefs.value[refKey][listLength - 1]

      if (lastRow) {
        lastRow.scrollIntoView({ behavior: 'smooth' })

        // 如果是折扣列表，增加额外的滚动偏移
        if (type === 'discountList') {
          const container = document.querySelector('.el-scrollbar__wrap')
          if (container) {
            container.scrollTop -= 36
          }
        }
      }
    }
  })
}

const closeContextMenu = () => {
  contextMenuVisible.value = false
}

const contextMenuRow = ref<items>({
  serialNumber: 0,
  matter: '',
  acceptor: '',
  billAmount: '',
  points: '',
  open: 0,
  rebate: '',
  interestDeduction: ''
  // `checked` 本身是可选的，可省略
})
const contextMenuType = ref('')
// 显示右键菜单
const showContextMenu = (
  event: MouseEvent,
  row: items, // 👈 这里用联合类型
  index: number,
  type: string
) => {
  console.log('showContextMenu')
  console.log(row)
  console.log(index)
  console.log(type)
  // 阻止默认右键菜单
  event.preventDefault()
  event.stopPropagation()
  // 设置菜单位置
  contextMenuPosition.x = event.clientX
  contextMenuPosition.y = event.clientY
  // 保存当前行数据和类型
  contextMenuRow.value = row
  contextMenuType.value = type
  // 显示菜单
  contextMenuVisible.value = true
}

const formatPrice = (amount) => {
  if (amount === null || amount === undefined || amount === '' || amount == '已走平') {
    return '已走平'
  }
  return `${amount}元`
}

// 向 Pinia 注册滚动函数
onMounted(() => {
  // 注册两个列表的滚动函数
  scrollStore.registerScrollHandler('discountList', () => scrollToLatestRow('discountList'))
  scrollStore.registerScrollHandler('buysList', () => scrollToLatestRow('buysList'))
})

// 卸载时清理
onUnmounted(() => {
  scrollStore.clearScrollHandler('discountList')
  scrollStore.clearScrollHandler('buysList')
})

// 监听全局点击事件关闭右键菜单
watch(
  () => tableDataStore.closeContextMenuFlag,
  () => {
    closeContextMenu()
  }
)

// 复制行数据
const handleCopyRow = () => {
  if (!contextMenuRow.value) return

  const type = contextMenuType.value
  let lens = type === 'discount' ? discountList.value.length : buysList.value.length
  lens = lens + 1

  // 复制行数据
  const row = contextMenuRow.value
  const newRow = {
    serialNumber: lens,
    matter: row.matter,
    acceptor: row.acceptor,
    billAmount: row.billAmount,
    points: row.points,
    open: row.open,
    rebate: row.rebate,
    interestDeduction: row.interestDeduction,
    checked: false
  }

  // 添加到对应列表
  tableDataStore.doSubmit(newRow, type === 'discount' ? 'discountList' : 'buysList')

  // 关闭菜单
  closeContextMenu()

  // 滚动到新行
  nextTick().then(() => {
    if (type === 'discount') {
      scrollStore.triggerScroll('discountList')
    } else {
      scrollStore.triggerScroll('buysList')
    }
  })

  ElMessage({
    message: '复制成功',
    type: 'success'
  })
}

// 删除行
const handleDeleteRow = () => {
  if (!contextMenuRow.value) return
  ElMessageBox.confirm('确定要删除该行吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    draggable: true,
    type: 'warning'
  })
    .then(() => {
      const type = contextMenuType.value
      tableDataStore.deleteRowRight(type == 'discount' ? 'discount' : 'buys', contextMenuRow.value)

      selectedRowIndex.value = -1
      selectedRowType.value = ''

      ElMessage({
        message: '删除成功',
        type: 'success'
      })
    })
    .catch(() => {
      // 取消删除
    })

  closeContextMenu()
}

const handleDeleteChooseRow = () => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    draggable: true,
    type: 'warning'
  })
    .then(() => {
      tableDataStore.deleteChooseRow()
      ElMessage({
        message: '删除成功',
        type: 'success'
      })
    })
    .catch(() => {
      // 取消删除
    })

  closeContextMenu()
}
import { pictureFun } from './utils/Capture'
const contentRef = ref<HTMLDivElement | null>(null)
const snapshotRef = ref<HTMLDivElement | null>(null)
const captureScreenshot = async () => {
  // if (tableDataStore.isCaptureMode) {
  isCaptureMode.value = true
  await pictureFun(contentRef, snapshotRef)
  isCaptureMode.value = false
  // }
}
// 监听截图信号变化
watch(
  () => tableDataStore.isCaptureMode,
  (signal) => {
    console.log('截图信号变化：', signal)
    // if (signal) {
    captureScreenshot()
    // }
  }
)

const discountCheckedAll = ref(false)
const buysCheckedAll = ref(false)
const handleCheckAll = (type: string) => {
  if (type === 'discountList') {
    tableDataStore.setItemsCheckedStatus(ArrayType.DISCOUNT, !discountCheckedAll.value)
  } else {
    tableDataStore.setItemsCheckedStatus(ArrayType.BUYS, !buysCheckedAll.value)
  }
}
</script>

<template>
  <div ref="contentRef" class="table-list">
    <!-- {{ currentItemIndex }} -- {{ currentItemType }} -->
    <!-- 用于截图的临时容器 -->
    <div ref="snapshotRef" class="snapshot-container" style="display: none"></div>
    <div class="head">
      <div class="heads-left">
        <div class="heads-icons">
          <img src="@/assets/bill/tb.png" alt="" srcset="" />
        </div>
        <div class="company-name">浙江网京</div>
        <div class="company-title">专业承兑服务</div>
      </div>
      <div class="heads-right">NO:{{ serial_number }}</div>
    </div>
    <el-scrollbar max-height="350px">
      <div v-if="buysLen > 0 || discountLen > 0">
        <!--  字体加粗 框 加粗 -->
        <table class="tables" border="0" cellspacing="0" cellpadding="0">
          <tbody ref="tableBody">
            <tr v-if="discountLen > 0">
              <th v-if="!isCaptureMode" style="width: 30px; font-weight: bold; color: #333">
                <el-checkbox
                  @click.stop
                  @click="handleCheckAll('discountList')"
                  v-model="discountCheckedAll"
                />
              </th>
              <th style="width: 60px; font-weight: bold; color: #333">序号</th>
              <th style="width: 60px; font-weight: bold; color: #333">事项</th>
              <th style="width: 120px; font-weight: bold; color: #333">承兑人信息</th>
              <th style="width: 160px; font-weight: bold; color: #333">票面金额(万元)</th>
              <th style="width: 100px; font-weight: bold; color: #333">点数</th>
              <th style="width: 100px; font-weight: bold; color: #333">张数</th>
              <th style="width: 160px; font-weight: bold; color: #333">贴息费(元)</th>
              <th style="width: 160px; font-weight: bold; color: #333">返点</th>
            </tr>
            <template v-if="discountLen > 0">
              <tr
                v-for="(item, index) in discountList"
                :key="index"
                :ref="(el: any) => setRowRef(el, 'discount', index)"
                :class="{
                  selected: index === selectedRowIndex && selectedRowType == 'discount',
                  'row-checked': item.checked
                }"
                @click.stop="selectRow(index, 'discount')"
                @contextmenu.prevent="showContextMenu($event, item, index, 'discount')"
              >
                <td v-if="!isCaptureMode">
                  <el-checkbox v-model="item.checked" @click.stop></el-checkbox>
                </td>
                <td>{{ item.serialNumber }}</td>
                <td>{{ item.matter }}</td>
                <td>{{ item.acceptor }}</td>
                <td>
                  {{ item.billAmount }}
                </td>
                <td>{{ item.points }}</td>
                <td>{{ item.open }}</td>
                <td>{{ item.interestDeduction }}</td>
                <td>{{ item.rebate }}</td>
              </tr>
            </template>
            <template v-if="buysLen > 0">
              <tr style="">
                <th
                  v-if="!isCaptureMode"
                  style="width: 30px; font-weight: bold; color: #333; z-index: 999"
                >
                  <el-checkbox
                    @click.stop
                    @click="handleCheckAll('buysList')"
                    v-model="buysCheckedAll"
                  />
                </th>
                <th style="width: 60px; font-weight: bold; color: #333">序号</th>
                <th style="width: 60px; font-weight: bold; color: #333">事项</th>
                <th style="width: 120px">
                  <div v-if="buysLen > 0 && discountLen < 1" style="font-weight: bold; color: #333">
                    承兑人信息
                  </div>
                  <div v-else>&nbsp;</div>
                </th>
                <th style="width: 160px">
                  <div v-if="buysLen > 0 && discountLen < 1" style="font-weight: bold; color: #333">
                    票面金额(万元)
                  </div>
                  <div v-else>&nbsp;</div>
                </th>
                <th style="width: 100px">
                  <div v-if="buysLen > 0 && discountLen < 1" style="font-weight: bold; color: #333">
                    点数
                  </div>
                  <div v-else>&nbsp;</div>
                </th>
                <th style="width: 100px">
                  <div v-if="buysLen > 0 && discountLen < 1" style="font-weight: bold; color: #333">
                    张数
                  </div>
                  <div v-else>&nbsp;</div>
                </th>
                <th style="width: 160px">
                  <div v-if="buysLen > 0 && discountLen < 1" style="font-weight: bold; color: #333">
                    贴息费(元)
                  </div>
                  <div v-else>&nbsp;</div>
                </th>

                <th style="width: 160px">
                  <div v-if="buysLen > 0 && discountLen < 1" style="font-weight: bold; color: #333">
                    返点
                  </div>
                  <div v-else>&nbsp;</div>
                </th>
              </tr>
              <tr
                v-for="(item, index) in buysList"
                :key="index"
                :ref="(el: any) => setRowRef(el, 'buy', index)"
                :class="{
                  selected: index === selectedRowIndex && selectedRowType == 'buy',
                  'row-checked': item.checked
                }"
                @click.stop="selectRow(index, 'buy')"
                @contextmenu.prevent="showContextMenu($event, item, index, 'buy')"
              >
                <td v-if="!isCaptureMode" @click.stop>
                  <el-checkbox v-model="item.checked"></el-checkbox>
                </td>
                <td>{{ item.serialNumber }}</td>
                <td>{{ item.matter }}</td>
                <td>{{ item.acceptor }}</td>
                <td>
                  {{ item.billAmount }}
                </td>

                <td>{{ item.points }}</td>
                <td>{{ item.open }}</td>
                <td>{{ item.interestDeduction }}</td>
                <td>{{ item.rebate }}</td>
              </tr>
            </template>
            <template v-if="buysLen > 0 || discountLen > 0">
              <tr class="total">
                <td colspan="10">
                  <div class="total-item">
                    <div class="total-item-title">{{ total.acceptor }}</div>
                    <div class="total-item-value" style="margin-right: 80px">
                      {{ formatPrice(total.billAmount) }}
                    </div>
                    <div class="total-item-title">{{ total.points }}</div>
                    <div class="total-item-value">
                      {{ formatPrice(total.interestDeduction) }}
                    </div>
                    <div class="total-item-value">{{ total.rebate }}</div>
                  </div>
                </td>
              </tr>
            </template>
            <tr
              v-if="
                special &&
                ((discountLen > 0 && buysLen == 0) ||
                  (buysLen > 0 && discountLen == 0) ||
                  (discountLen > 0 &&
                    buysLen > 0 &&
                    Number(discountTotal.billAmount) > Number(buyTotal.billAmount)))
              "
            >
              <td colspan="10">
                <div class="special">
                  <template v-if="isBillingBoolean">
                    <span style="color: royalblue">
                      &nbsp;开票&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    </span>
                  </template>
                  <template v-if="discountLen > 0 && buysLen == 0">
                    扣息回款: {{ discountTotal.billAmount }} -
                    {{ discountTotal.interestDeduction }} =
                    {{ specialNum }}
                    元
                  </template>
                  <template v-else-if="buysLen > 0 && discountLen == 0">
                    返点回款: {{ buyTotal.billAmount }} - {{ buyTotal.rebate }} =
                    {{ specialNum }}
                    元
                  </template>
                  <template
                    v-else-if="
                      discountLen > 0 &&
                      buysLen > 0 &&
                      Number(discountTotal.billAmount) > Number(buyTotal.billAmount)
                    "
                  >
                    扣息回款: {{ total.billAmount }} - {{ total.interestDeduction }} =
                    {{ specialNum }}
                    元
                  </template>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <div v-else>
        <el-empty description="暂无数据" />
      </div>
    </el-scrollbar>
    <ContextMenu
      :visible="contextMenuVisible"
      :position="contextMenuPosition"
      @copy="handleCopyRow"
      @delete="handleDeleteRow"
      @deleteChoose="handleDeleteChooseRow"
    />
  </div>
</template>

<style lang="scss" scoped>
.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
  cursor: pointer;
  transition: background-color 0.3s ease;
}
.special {
  display: flex;
  align-items: center;
  justify-content: center;
  color: red;
  font-size: 20px;
}
.table-list {
  margin-top: 10px;
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 1;
  /* Table style */
  table {
    width: 100%;
  }
  th,
  td {
    padding: 2px;
    border: 1px solid #eee; /* 边框颜色对比 */
    // border: 2px double #eaeaea; /* 边框颜色对比 */
    // border: 1px solid #ddd;
    // text-align: left;
    text-align: center;
    // font-weight: bold;
    // border: 2px solid #fff;
  }
  th {
    position: sticky;
    top: 0; /* 标题行固定在顶部 */
    background-color: #f2f2f2;
    // color: #fff;
    // font-weight: bold;
    z-index: 100; /* 提高表头层级 */
  }

  /* 新增：确保表头背景不透明 */
  thead {
    background-color: #f2f2f2;
    position: relative;
    z-index: 100;
  }

  .total {
    background-color: #134e88;
    color: white;
    .total-item {
      display: flex;
      justify-content: center;
      width: 100%;
      .total-item-title {
        padding: 0 10px;
      }
      .total-item-content {
        // width: 100px;
        padding: 0 10px;
      }
    }
  }
  .head {
    height: 60px;
    width: 100%;
    background: radial-gradient(circle, #fcccbc, #f4ba97);
    display: flex;
    justify-content: space-between;
  }
  .heads-left {
    display: flex;
  }
  .heads-left .company-name {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 30px;
    font-weight: bold;
    font-family: Inter, 'Microsoft YaHei', serif;
  }
  .heads-left .company-title {
    display: flex;
    justify-content: center;
    align-items: flex-end;
    margin-bottom: 10px;
    margin-left: 10px;
    font-size: 18px;
    font-weight: bold;
    color: #0d84ff;
    font-family: Inter, 'Microsoft YaHei', serif;
  }
  .heads-icons {
    width: 80px;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .heads-icons img {
    width: 50px;
  }
  .heads-right {
    display: flex;
    justify-content: flex-end;
    align-items: flex-end;
    margin-bottom: 10px;
    margin-right: 10px;
    font-size: 16px;
  }
}

.row-checked {
  background-color: #ffeb3b; /* 自定义背景颜色 */
  // background-color: #f0f8ff; /* 自定义背景颜色 */
}
.table-header {
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 1;
}
.custom-input {
  border: 1px solid #999; /* 设置边框样式 */
  border-radius: 4px; /* 设置圆角 */
}

// 右键菜单样式
.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #eee;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  padding: 5px 0;
  z-index: 9999;

  &-item {
    padding: 8px 16px;
    cursor: pointer;
    font-size: 14px;

    &:hover {
      background-color: #f5f7fa;
    }
  }
}
.selected {
  background-color: #f0f0f0;
}
</style>
